package com.jpyl.jpMedicalTreatment.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.forxindu.kit.box.JavaKit;
import com.forxindu.kit.box.VerifyKit;
import com.forxindu.kit.box.ViewKit;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.common.MedicalSettings;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;

import butterknife.BindView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 521546564465 on 2019/1/12.
 */

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.phone_number)
    EditText userPhoneNumber;

    @BindView(R.id.password_word)
    EditText password;

    @BindView(R.id.password_word_again)
    EditText passwordAgain;

    @BindView(R.id.auth_code)
    EditText authCode;

    @BindView(R.id.inviter_info)
    EditText inviterInfo;

    @BindView(R.id.send_auth_code)
    TextView sendAuthCode;

    @BindView(R.id.send_message_layout)
    RelativeLayout sendMessageLayout;


    EventHandler eventHandler = new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            // afterEvent会在子线程被调用，因此如果后续有UI相关操作，需要将数据发送到UI线程
            Message msg = new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理成功得到验证码的结果
                            // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                            ViewKit.showToast(RegisterActivity.this, "验证码已发送");
                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
                        }
                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理验证码验证通过的结果
                            Register();
                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
                            ViewKit.showToast(RegisterActivity.this, "验证码错误");
                        }
                    }
                    // TODO 其他接口的返回结果也类似，根据event判断当前数据属于哪个接口
                    return false;
                }
            }).sendMessage(msg);
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.common_register_layout;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        mTitleTv.setText("注册");
        // 注册一个事件回调，用于处理SMSSDK接口请求的结果
        SMSSDK.registerEventHandler(eventHandler);

        sendAuthCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String username = userPhoneNumber.getText().toString().trim();
                if (JavaKit.isStringEmpty(username)) {
                    ViewKit.showToast(RegisterActivity.this, getString(R.string.login_mobile));
                    return;
                }
                if (!VerifyKit.isMobile(username)) {
                    ViewKit.showToast(RegisterActivity.this, getString(R.string.find_password_correct_mobile));
                    return;
                }
                countDown();
                // 请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
                SMSSDK.getVerificationCode("86", username);
            }
        });

        passwordAgain.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setRegisterButtonStatus();
            }
        });

        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setRegisterButtonStatus();
            }
        });

        sendMessageLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String username = userPhoneNumber.getText().toString().trim();
                final String pwd = password.getText().toString().trim();
                final String pwdAgain = passwordAgain.getText().toString().trim();
                final String authCodeText = authCode.getText().toString().trim();
                if (TextUtils.isEmpty(username)) {
                    ViewKit.showToast(RegisterActivity.this, getResources().getString(R.string.User_name_cannot_be_empty));
                    return;
                }
                if (TextUtils.isEmpty(pwd) && TextUtils.isEmpty(pwdAgain)) {
                    ViewKit.showToast(RegisterActivity.this, getResources().getString(R.string.Password_cannot_be_empty));
                    return;
                }
                if (TextUtils.isEmpty(authCodeText)) {
                    ViewKit.showToast(RegisterActivity.this, "验证码不能为空");
                    return;
                }
                if (!pwd.equals(pwdAgain)) {
                    ViewKit.showToast(RegisterActivity.this, "两次密码输入不一致，请重新输入");
                    return;
                }
                // 提交验证码，其中的code表示验证码，如“1357”
                SMSSDK.submitVerificationCode("86", username, authCodeText);
            }
        });
    }

    /**
     * 倒数计时
     */
    @SuppressLint("ResourceAsColor")
    private void countDown() {
        new CountDownTimer(MedicalSettings.COUNT_DOWN_TIME, 1000) {

            public void onTick(long millisUntilFinished) {
                String againSendInfo = getResources().getString(R.string.find_password_again_send_info);
                String againSendInfoText = String.format(againSendInfo, String.valueOf(millisUntilFinished / 1000));
                sendAuthCode.setText(Html.fromHtml(againSendInfoText));
                sendAuthCode.setBackgroundResource(R.drawable.round_corner_gray_bg_shape10);
                sendAuthCode.setTextColor(getResources().getColor(R.color.gray_AAAAAA));
                sendAuthCode.setClickable(false);
            }

            public void onFinish() {
                sendAuthCode.setText(getString(R.string.find_password_auth_code));
                sendAuthCode.setBackgroundResource(R.drawable.btn_feed_back_shape);
                sendAuthCode.setTextColor(getResources().getColor(R.color.white));
                sendAuthCode.setClickable(true);
            }
        }.start();
    }

    private void setRegisterButtonStatus() {

        final String username = userPhoneNumber.getText().toString().trim();
        final String pwd = password.getText().toString().trim();
        final String pwdAgain = passwordAgain.getText().toString().trim();
        final String authCodeText = authCode.getText().toString().trim();
        if (!TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(pwdAgain)) {
            if (username.length() >= 11 && pwd.length() >= 6 && pwdAgain.length() >= 6 && authCodeText.length() >= 4 && pwdAgain.equals(pwd)) {
                sendMessageLayout.setBackgroundResource(R.drawable.round_corner_blue_bg_shape10);
            } else {
                sendMessageLayout.setBackgroundResource(R.drawable.round_corner_gray_bg_shape10);
            }
        }
    }

    final RequestApi publicApi = Network.getRequestApi();

    //注册
    void Register() {

        final String username = userPhoneNumber.getText().toString().trim();
        final String pwd = password.getText().toString().trim();
        //邀请人，邀请人则增加积分
        String inviter = inviterInfo.getText().toString().trim();

        publicApi.jpylRegister(username, pwd, inviter).map(new Func1<ResponseModel<String>,
                String>() {
            @Override
            public String call(ResponseModel<String> responseModel) {
                if (responseModel.getCode() != 0) {
                    String msg = responseModel.getMsg();
                    throw new ApiError(responseModel.getCode(), msg);
                }
                return responseModel.getMsg();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(RegisterActivity.this, error.getMsg() + "");
                        }
                    }

                    @Override
                    public void onNext(String msg) {
                        ViewKit.showToast(RegisterActivity.this, msg + "");
                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }
                });
    }

    // 使用完EventHandler需注销，否则可能出现内存泄漏
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }

}
